/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 *
 * @author Administrador
 */
public class ImageUtil {

    public static BufferedImage readImage(String filename) throws IOException {
        return ImageIO.read(new File(filename));
    }

    public static void writeImage(BufferedImage image, String filetype, String filename) throws IOException {
        ImageIO.write(image, filetype, new File(filename));
    }

    public static BufferedImage[][] splitImage(BufferedImage image, int rows, int cols) {
        BufferedImage[][] tmp = new BufferedImage[rows][cols];
        int newWidth = image.getWidth() / cols;
        int newHeight = image.getHeight() / rows;
        System.out.println("X:" + newWidth + " Y: " + newHeight );
        int m, n, x, y;
        for (m = 0; m < rows; m++) {
            y = newHeight * m;
            for (n = 0; n < cols; n++) {
                x = newWidth * n;
                tmp[m][n] = image.getSubimage(x, y, newWidth, newHeight);
            }
        }
        return tmp;
    }








    public static BufferedImage resizeImage(BufferedImage image, float escale) {
        int newWitdh = (int) (image.getWidth() * escale);
        int newHeight = (int) (image.getHeight() * escale);
        return resizeImage(image, newWitdh, newHeight);
    }

    public static BufferedImage resizeImage(BufferedImage image, float escaleWitdh, float escaleHeight) {
        int newWitdh = (int) (image.getWidth() * escaleWitdh);
        int newHeight = (int) (image.getHeight() * escaleHeight);
        return resizeImage(image, newWitdh, newHeight);
    }

    public static BufferedImage resizeImage(BufferedImage image, int newWitdh, int newHeight) {
        BufferedImage tmp = new BufferedImage(newWitdh, newHeight, image.getType());
        Graphics2D g2D = tmp.createGraphics();
        g2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2D.drawImage(image, 0, 0, newWitdh, newHeight, 0, 0, image.getWidth(), image.getHeight(), null);
        g2D.dispose();
        return tmp;
    }


    
    public static BufferedImage rotateImage(BufferedImage image, int angle) {
        return rotateImage(image, angle, image.getWidth() / 2, image.getHeight() / 2 );
    }

    public static BufferedImage rotateImage(BufferedImage image, int angle, int x, int y) {
        BufferedImage tmp = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
        Graphics2D g2D = tmp.createGraphics();
        g2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2D.rotate(Math.toRadians(angle), x, y);
        g2D.drawImage(image, null, 0, 0);
        return tmp;
    }
}
